﻿<p class="bold large">Write the method digitSum that takes in an integer as a parameter and returns the sum of the digits (return a negative number if the value that was passed in is negative)</p>
<p>If 786 were passed in then 21 would be returned</p>
<p>If -241 were passed in then -7 would be returned</p>
<div class="practiceAccordion">
    <h3>Hints</h3>
    <div>
        <ul>
            <li>Create a sum variable</li>
            <li>Use a loop to iterate through the digits of the integer</li>
            <li>Make use of %10 (mod 10) and /10 (divided by 10) so that you can get the value of the ones digit and then shift the number down one digit (think integer division)</li>
        </ul>
    </div>
    <h3>Possible Solution</h3>
<p class="format code">public static int digitSum(int num) {
    int sum = 0;

    while(num != 0) {
        sum += (num % 10);
        num /= 10;
    }

    return sum;
}
</p>
            </div>
<a href="#practiceTop">Back to top</a>